<template>
  <a-upload
    v-model:file-list="fileList"
    :accept="accept"
    list-type="picture-card"
    :headers="headers"
    :show-upload-list="false"
    :action="action"
    :before-upload="beforeUpload"
    @change="change"
  >
    <img style="width: 200px" v-if="fileUrl" :src="fileUrl" alt="avatar" />
    <div v-else>
      <loading-outlined v-if="loading"></loading-outlined>
      <plus-outlined v-else></plus-outlined>
      <div class="ant-upload-text">上传</div>
    </div>
  </a-upload>
</template>
<script lang="ts">
import { defineComponent, ref } from "vue";
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons-vue";
import env from "/@/base/env";
import { Api } from "/@/api/common";
import { IMG_EXT } from "/@/utils/img";
import { AuthenticationScheme } from "/@/api/req";
import authCache from "/@/utils/cache/authCache";
import { message } from "ant-design-vue";

interface Response {
  code: number;
  url: string;
}

interface FileItem {
  uid: string;
  name?: string;
  status?: string;
  response?: Response;
  url: string;
}

interface FileInfo {
  file: FileItem;
  fileList: FileItem[];
}
const UPDATE_FILE_URL_EVENT = "update:fileUrl";
export default defineComponent({
  components: { LoadingOutlined, PlusOutlined },
  emits: [UPDATE_FILE_URL_EVENT],
  props: {
    fileUrl: String,
  },
  setup(props, ctx) {
    const action = env.baseUrl + Api.upload;
    const fileList = ref([]);
    const accept = IMG_EXT;
    const loading = ref(false);
    const token = authCache.getToken();
    const headers = {
      Authorization: `${AuthenticationScheme} ${token}`,
    };
    function beforeUpload() {}
    function change(info: FileInfo) {
      if (info.file.status === "uploading") {
        loading.value = true;
        return;
      } else if (info.file.status === "done") {
        loading.value = false;
        // Get this url from response in real world.
        const res = info.file.response;
        if (res && res.code === 200) {
          ctx.emit(UPDATE_FILE_URL_EVENT, res.url);
        } else {
          message.error("上传失败，请稍候再试");
        }
      } else if (info.file.status === "error") {
        loading.value = false;
        message.error("上传失败，请稍候再试");
      }
    }
    return {
      fileList,
      action,
      accept,
      beforeUpload,
      change,
      loading,
      headers,
    };
  },
});
</script>
